//
//  ViewController.swift
//  jishua
//
//  Created by du on 2024/4/29.
//

import UIKit
import MLKit

class ViewController: UIViewController {
    
    @IBOutlet weak var imageView: UIImageView!
    var limit = 100
    var textRecognizer:TextRecognizer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.imageView.contentMode = .scaleAspectFit // 根据内容缩放以适应 UIImageView
        ocrInit()
    }
    
    @IBAction func startBtnUp(_ sender: Any) {
        NSLog("test")

        // 安全地尝试获取文件路径，这里只是示例，实际路径取决于你的应用如何访问此文件
//        let documentsDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
//        let fileURL = documentsDirectory.appendingPathComponent("/Library/ZXTouch/scripts/Debug/test.jpg")
        let homeDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        print("路径：", homeDirectory)
        let fileURL = URL(fileURLWithPath: "\(homeDirectory)/test123.jpg")

        if let imageData = try? Data(contentsOf: fileURL), let image = UIImage(data: imageData) {
            // 假设有个UIImageView实例名叫imageView
            imageView.image = image
            
            let visionImage = VisionImage(image: image)
            visionImage.orientation = image.imageOrientation
            
            textRecognizer?.process(visionImage) { result, error in
              guard error == nil, let result = result else {
                // Error handling
                  print("error")
                return
              }
              // Recognized text
                print(result)
            }
        } else {
            print("未能加载图片，可能是路径无效或无权访问")
        }
    }
    
    private func ocrInit(){
        let chineseOptions = ChineseTextRecognizerOptions()
        textRecognizer = TextRecognizer.textRecognizer(options:chineseOptions)
    }

}

